package com.gitee.ixtf.sap.kotlinx

import com.fasterxml.jackson.databind.JsonNode
import com.sap.conn.jco.JCoFunction
import com.sap.conn.jco.JCoRecord

fun JCoFunction.fillData(body: JsonNode) {
  importParameterList?.fillData(body)
  changingParameterList?.fillData(body)
  tableParameterList?.fillData(body)
}

private fun JCoRecord.fillData(body: JsonNode) {
  forEach { field ->
    body.get(field.name)?.also { value ->
      when {
        field.isTable -> {
          val table = field.table
          value.forEach {
            table.appendRow()
            table.fillData(it)
          }
        }
        field.isStructure -> field.structure.fillData(value)
        else -> field.setValue(value.asText())
      }
    }
  }
}

fun JCoFunction.jsonMap(): Map<String, Any?> = buildMap {
  exportParameterList?.let { putAll(it.jsonMap()) }
  changingParameterList?.let { putAll(it.jsonMap()) }
  tableParameterList?.let { putAll(it.jsonMap()) }
}

private fun JCoRecord.jsonMap(): Map<String, Any?> = buildMap {
  this@jsonMap.forEach { field ->
    when {
      field.isTable -> {
        val table = field.table
        val list =
            (0 until table.numRows).map { row ->
              table.row = row
              table.jsonMap()
            }
        put(field.name, list)
      }
      field.isStructure -> put(field.name, field.structure.jsonMap())
      else -> put(field.name, field.value)
    }
  }
}
